I have written a deep equality check function. I am getting this error for highlighted lines.
Can anyone suggest what I need to do to fix this error (or at least what the error means).
Code:
export const deepEqual = (object1: any, object2: any) => {
const keys1 = Object.keys(object1);
const keys2 = Object.keys(object2);
if (keys1.length !== keys2.length) {
return false;
}
for (const key of keys1) {
const val1: unknown = object1[key] as unknown; // Error for this line
const val2: unknown = object2[key] as unknown; // Error for this line
const areObjects = isObject(val1) && isObject(val2);
if (
(areObjects && !deepEqual(val1, val2)) ||
(!areObjects && val1 !== val2)
) {
return false;
}
}
return true;
};
Error:
45:27 error Unsafe member access [key] on an any value @typescript-eslint/no-unsafe-member-access
45:27 error Unsafe member access [key] on an any value @typescript-eslint/no-unsafe-member-access
The errors mean, that you try to access a property (or member) of an object with type any. any in TS gives you no clues or knowledge about the values behind the variables.
ESLint displays an error, since accessing members of objects with type any can lead to unwanted (and maybe undetected) bugs. Your code will still compile, since TypeScript on its own has no problems with that. If you really know what you are doing, you can disable ESLint for certain lines by commenting
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
above them.